package maa.action.client;

import maa.action.Action;
import maa.action.ActionResult;
import maa.dao.DAOCommand;
import maa.dao.DAOFactory;
import maa.dao.DAOManager;
import maa.database.ConnectionPool;
import maa.entity.User;
import maa.action.ActionException;
import maa.dao.DAOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

public class UnsubscribeFromCourse implements Action {
    @Override
    public ActionResult execute(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        HttpSession session = req.getSession();
        ActionResult actionResult = new ActionResult();
        ConnectionPool connectionPool = ConnectionPool.getInstance();
        DAOManager daoManager = DAOFactory.createDAOManager(connectionPool.getConnection());
        String string = req.getParameter("course-uuid").substring(0, req.getParameter("course-uuid").length() - 1);
        final UUID uuid = UUID.fromString(string);
        final User user = (User) session.getAttribute("user");
        DAOCommand command = new DAOCommand() {
            @Override
            public Object execute(DAOManager daoManager) throws ActionException {
                try {
                    return daoManager.getClientDAO().removeCourse(user, uuid);
                } catch (DAOException e) {
                    throw new ActionException("Exception in clientDAO.removeCourse(user, uuid)");
                }
            }
        };
        Boolean flag = (Boolean) daoManager.executeAndClose(command);
        if(flag) {
            actionResult.setResult("account");
            actionResult.setRedirected(true);
        }
        return actionResult;

    }
}
